package com.gitee.l0km.javadocreader;

import static com.gitee.l0km.javadocreader.JavadocReader.read;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.List;

import com.gitee.l0km.com4j.basex.doc.ClassCommentProvider;
import com.google.common.collect.ImmutableList;

public class ClassCommentProviderImpl implements ClassCommentProvider {
	
	private final ExtClassDoc classDoc;
	private final Class<?> clazz;
	
	public ClassCommentProviderImpl(Class<?> clazz) {
		this.clazz = clazz;
		this.classDoc = read(clazz);
	}

	@Override
	public List<String> commentOfClass() {
		if(classDoc  == null){
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getClassCommentAsList(false,false, true);
		return cmt  == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

	@Override
	public List<String> commentOfMethod(Method method, boolean withTags) {
		if (classDoc == null) {
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getMethodCommentAsList(method, false, false, withTags);
		return cmt == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

	@Override
	public List<String> commentOfField(String name) {
		if (classDoc == null) {
			return ImmutableList.of();
		}
		List<String> cmt = classDoc.getFieldCommentAsList(name, false, false, false);
		if (cmt == null) {
			try {
				PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
				Method rm = propertyDescriptor.getReadMethod();
				if (rm != null) {
					return commentOfMethod(rm, false);
				}
				Method wm = propertyDescriptor.getWriteMethod();
				if (wm != null) {
					return commentOfMethod(wm, false);
				}
			} catch (IntrospectionException e) {
				// DO NOTHING
			}

		}
		return cmt == null ? ImmutableList.<String>of() : ImmutableList.copyOf(cmt);
	}

}
